package gui.symbols;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;


public class SymbolListModel implements ListModel{

  private List<ListDataListener> listDataListeners;
  private List<Symbol> symbolList;
  
  public SymbolListModel(){
    listDataListeners = new ArrayList<ListDataListener>();
    symbolList = new ArrayList<Symbol>();
  }
  
  public void setFields(Map<Integer, String> fields){
    int size = symbolList.size();
    symbolList.clear();
    
    Iterator<Map.Entry<Integer, String>> it = fields.entrySet().iterator();
    while (it.hasNext()) {
      symbolList.add(new Symbol((Map.Entry<Integer, String>)it.next()));
    }
    Collections.sort(symbolList);
    
    if(size < symbolList.size())
      size = symbolList.size();
    
    for(ListDataListener l : listDataListeners)
      l.contentsChanged( new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, size));      
  }
  
  public void addListDataListener(ListDataListener l) {
    listDataListeners.add(l);
  }

  public Object getElementAt(int index) {
    return symbolList.get(index);
  }

  public int getSize() {
    return symbolList.size();
  }

  public void removeListDataListener(ListDataListener l) {
    listDataListeners.remove(l);
  }

  public void clear(){
    int size = symbolList.size();
    symbolList.clear();
    for(ListDataListener l : listDataListeners)
      l.contentsChanged( new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, size));
  }
  
  public void addField(Symbol s){
    symbolList.add(s);
    Collections.sort(symbolList);
    for(ListDataListener l : listDataListeners)
      l.contentsChanged( new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, symbolList.size()));
  }
}
